<?php

declare(strict_types=1);

namespace app\official\controller;

use app\BaseController;
use app\common\model\Config as ConfigModel;
use app\common\model\Post\Post as PostModel;
// easyWeChat的类
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Messages\Text;
use Exception;

class Index extends BaseController
{
    // 初始化
    protected function initialize()
    {
        parent::initialize();

        // 读取配置文件的参数
        $config = config('officialAccount');

        // 初始化
        $this->weChat = Factory::officialAccount($config);
    }

    public function auth()
    {
        try {
            $this->weChat->server->push(function ($message) {

                switch ($message['MsgType']) {
                    case 'event':
                        return $this->event($message);
                        break;
                    case 'text':
                        return $this->text($message);
                        break;
                    case 'image':
                        return '收到图片消息';
                        break;
                    case 'voice':
                        return '收到语音消息';
                        break;
                    case 'video':
                        return '收到视频消息';
                        break;
                    case 'location':
                        return '收到坐标消息';
                        break;
                    case 'link':
                        return '收到链接消息';
                        break;
                    case 'file':
                        return '收到文件消息';
                        // ... 其它消息
                    default:
                        return '收到其它消息';
                        break;
                }
            });
        } catch (\Throwable $th) {
            //throw $th;
        }

        // 推送公众号操作
        $response = $this->weChat->server->serve();

        // 将响应输出
        $response->send();
        exit; // Laravel 里请使用：return $response;
    }

    // 事件信息
    public function event($message)
    {

        if ($message['Event'] == 'subscribe') {
            return new Text("欢迎来到测试号\n使用帮助菜单\n1、发送城市名称，可搜索天气\n2、发送预约单号，可搜索预约进度\n3、发送商品订单号，可搜索商品订单进度\n4、发送悬赏问题，可查看解决方案(提问：关键词)");
        }

        if ($message['EventKey'] == 'V1001_GOOD') {
            return new Text('点赞成功');
        }
    }

    // 文本信息
    public function text($message)
    {
        $HelpList = [1, 'h', 'help', '帮助'];

        if (in_array($message['Content'], $HelpList)) {
            return new Text("欢迎来到测试号\n使用帮助菜单\n1、发送城市名称，可搜索天气\n2、发送预约单号，可搜索预约进度\n3、发送商品订单号，可搜索商品订单进度\n4、发送悬赏问题，可查看解决方案(提问：关键词)");
        }

        // 城市+天气
        if (strpos($message['Content'], '天气') !== FALSE) {
            // 获取用户输入的内容
            $content = $message['Content'];

            // 用正则匹配关键字
            preg_match('/^(.*)天气$/', $content, $result);

            // 获取城市
            $city = !empty($result[1]) ? $result[1] : '';


            if (!$city) {
                return new Text('请输入需要城市');
            }

            // api地址 + key + 城市
            $ApiUrl = "http://apis.juhe.cn/simpleWeather/query?city=$city&key=9ab6176129dbb280b54721e4da1a1e78";

            // 获取文件是否存在
            $File = is_file(public_path() . 'Weather/' . $city . '.json') ? file_get_contents(public_path() . 'Weather/' . $city . '.json') : '';

            if ($File) {
                $FileTime = filemtime(public_path() . 'Weather/' . $city . '.json');

                if ((time() - $FileTime) > 3600) {
                    $json = file_get_contents($ApiUrl);

                    $length = file_put_contents(public_path() . 'Weather/' . $city . '.json', $json);

                    if ($length < 0) {
                        return new Text('暂无无法获取天气');
                    }
                }
            } else {

                // 获取查询城市天气
                $json = file_get_contents($ApiUrl);

                if (!is_dir(public_path() . 'Weather')) {
                    mkdir(public_path() . 'Weather');
                }

                // public_path => public入口文件夹
                $length = file_put_contents(public_path() . 'Weather/' . $city . '.json', $json);

                if ($length < 0) {
                    return new Text('暂无无法获取天气');
                }
            }

            $FileRes = file_get_contents(public_path() . 'Weather/' . $city . '.json');

            $data = json_decode($FileRes, true);

            // 根据错误码显示错误信息
            switch ($data['error_code']) {
                case 10011:
                    return new Text('您当前请求过多，请稍后再试');
                    break;

                case 10012:
                    return new Text('当前请求过多，请稍后再试');
                    break;

                case 10020:
                    return new Text('该功能正在维护中');
                    break;

                case 10021:
                    return new Text('该功能停用~');
                    break;

                case 207302:
                    return new Text('查询不到该城市的相关信息');
                    break;

                case 207301:
                    return new Text('错误的查询城市名,请重新查询');
                    break;

                case 207303:
                    return new Text('网络错误，请重试');
                    break;
            }

            // 获取result的数据
            $data = $data['result'];

            $output = "{$data['city']}当前天气情况：\n天气情况：{$data['realtime']['info']}\n温度：{$data['realtime']['temperature']}℃\n湿度：{$data['realtime']['humidity']}℃\n风向：{$data['realtime']['direct']}\n风力：{$data['realtime']['power']}\n空气质量指数：{$data['realtime']['aqi']}";

            return new Text($output);
        }

        // 提问：vue
        if (strpos($message['Content'], '提问') !== FALSE) {
            $content = preg_replace('/：|:/', ':', $message['Content']);

            preg_match('/^提问:(.*)$/', $content, $result);

            $title = isset($result[1]) ? $result[1] : '';

            if (!$title) {
                return new Text('请输入提问的关键字');
            }

            $where[] = ['title', 'like', "%$title%"];

            $post = PostModel::where($where)->find();

            $cdn = ConfigModel::where('key', 'cdn')->value('value');

            $items = [
                new NewsItem([
                    'title' => $post['title'],
                    'image' => $cdn . '/static/home/res/images/logo.png',
                    'url' => $cdn . '/home/post/info.html?postid=' . $post['id']
                ])
            ];

            return new News($items);
        }

        $content = $message['Content'];
        // 智能机器人
        $ApiUrl = "http://api.qingyunke.com/api.php?key=free&appid=0&msg={$content}";
        // res=>对象
        $res = file_get_contents($ApiUrl);
        // 对象转数组
        $result = (array)json_decode($res, true);
        return new Text($result['content']);
    }

    // 创建菜单
    public function menu()
    {
        $appid = 'wxa5f1bf8661d5a315';
        $secret = '0418b0e27648aa87de61e67afc982438';
        $ACCESS_TOKEN = $this->getAccessToken($appid, $secret);
        $menu = '{"button":[
            {
                "name" : "菜单",
                "sub_button" : [
                    {
                        "type" => "view",
                        "name" => "搜索",
                        "url"  => "http://www.soso.com/"
                    },
                    {
                        "type" => "view",
                        "name" => "视频",
                        "url"  => "http://v.qq.com/"
                    },
                    {
                        "type" => "click",
                        "name" => "赞一下我们",
                        "key" => "V1001_GOOD"
                    }],
            },
            {
                "name":"更多",
                "sub_button":[
                  {
                     "type":"view",
                     "name":"论坛",
                     "url":"https://www.ask.lutianyao.con"
                  },
                  {
                     "type":"view",
                     "name":"后台",
                     "url":"https://www.ask.lutianyao.con/admin"
                  },
                  {
                     "type": "view_limited", 
                     "name": "联系我们", 
                     "media_id": ""
                  },
                  {
                     "type":"view",
                     "name":"商城",
                     "url":"https://www.shop.lutianyao.con"
                  }]
            }]
        ]}';
        $ch = curl_init();

        curl_setopt(
            $ch,
            CURLOPT_URL,
            "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$ACCESS_TOKEN}"
        );
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt(
            $ch,
            CURLOPT_USERAGENT,
            'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'
        );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $menu);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Errno' . curl_error($ch);
        }
        curl_close($ch);
        print_r($res);
    }

    public function getAccessToken($appid, $secret)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $res = $this->curl_get($url);
        $res = json_decode($res, true);
        return $res['access_token'];
    }
    public function curl_get($url)
    {
        $headers = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36');
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 20);
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
    // 发送模板信息
    public function send()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();

            $result = $this->weChat->template_message->send([
                'touser' => $params['touser'],
                'template_id' => 'XahPPwSpnS74A90wf96mw9x-SeE9Bsyi5uc9hIhsFtU',
                // 'url' => 'https://easywechat.org',
                // 'miniprogram' => [
                //         'appid' => 'xxxxxxx',
                //         'pagepath' => 'pages/xxx',
                // ],
                'data' => [
                    'first' => [
                        'value' => '下单成功',
                        'color' => '#173177'
                    ],
                    'code' => [
                        'value' => $params['code'],
                        'color' => '#173177'
                    ],
                    'name' => [
                        'value' => $params['name'],
                        'color' => '#173177'
                    ],
                    'content' => [
                        'value' => $params['content'],
                        'color' => '#173177'
                    ],
                    'createtime' => [
                        'value' => date("Y-m-d H:i:s", time()),
                        'color' => '#173177'
                    ],
                ],
            ]);

            if ($result === FALSE) {
                echo '发送失败';
                exit;
            } else {
                echo '发送成功';
                exit;
            }
        }
        return view();
    }
}
